import React, { useState, useRef, useEffect, useContext } from "react"
import { Button, Form, Input, Modal, message } from "antd"
import ReactDOM from "react-dom"
import { UserContext, updateUser, useUserContext, useUserDispatchContext } from "@/providers/UserContextProvider"
import { createApiClient } from "@/utils/api_client"

const LoginModal = () => {
    const [username, setUsername] = useState("")
    const [password, setPassword] = useState("")

    const user = useUserContext()
    useEffect(() => {
        const pathname = window.location.pathname
        setOpenState(user.token === "TokenInvalid" && pathname != "/login")
    }, [user])
    const [openState, setOpenState] = useState(false)
    const [messageApi, contextHolder] = message.useMessage()
    const { login } = createApiClient(useUserDispatchContext())

    return (
        <>
            {contextHolder}
            <Modal
                title="登录"
                open={openState}
                onCancel={() => setOpenState(false)}
                onOk={() => {
                    login(username, password)
                        .then(() => message.success("登录成功"))
                        .catch(err => {
                            messageApi.error(err.message)
                        })
                }}
            >
                <Form layout="vertical" onFinish={() => console.log("submit...")}>
                    <Form.Item label="用户名" name="username" rules={[{ required: true, message: "请输入用户名" }]}>
                        <Input value={username} onChange={e => setUsername(e.target.value)} />
                    </Form.Item>
                    <Form.Item label="密码" name="password" rules={[{ required: true, message: "请输入密码" }]}>
                        <Input type="password" value={password} onChange={e => setPassword(e.target.value)} />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    )
}
export { LoginModal }
